package org.springblade.common.io;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.InputStream;

public class XorInputStream extends InputStream {

	public static final int KEY=2;

    private InputStream inputStream;

    public XorInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }
    @Override
    public int read() throws IOException {
        int readContent = this.inputStream.read();
        if (readContent != -1) {
            readContent = readContent^KEY;
        }
        return readContent;
    }

    @Override
    public int read(@NotNull byte[] b, int off, int len) throws IOException {
        int readLen = this.inputStream.read(b, off, len);
        if (readLen != -1) {
            for (int i = 0; i < readLen; i++) {
                b[off + i] = (byte) (b[off + i]^KEY);
            }
        }
        return readLen;
    }

    public byte[] readAllBytes(int available) {
        byte[] bytes = new byte[available];
        try {
            int readLen = read(bytes, 0, available);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }

    @Override
    public int read(@NotNull byte[] b) throws IOException {
        return super.read(b);
    }

    @Override
    public void close() throws IOException {
        this.inputStream.close();
    }

    @Override
    public int available() throws IOException {
        return this.inputStream.available();
    }
}
